package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.OrderTo;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WmsFeignService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
//import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    private ThreadLocal<OrderSubmitVo> submitVoThreadLocal = new ThreadLocal<>();
    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private CartFeignService cartFeignService;
    @Autowired
    ThreadPoolExecutor executor;
    @Autowired
    private WmsFeignService wmsFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        System.out.println("主线程..." + Thread.currentThread().getId());
        //获取之前的请求
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            System.out.println("getAddressFuture线程..." + Thread.currentThread().getId());
            //每一个线程都共享之前的请求
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //1.远程查询所有收获地址列表
            List<MemberAddressVo> addresses = memberFeignService.getAddress(memberRespVo.getId());
            orderConfirmVo.setAddresses(addresses);
        }, executor);
        CompletableFuture<Void> getItemsFuture = CompletableFuture.runAsync(() -> {
            System.out.println("getItemsFuture线程..." + Thread.currentThread().getId());
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //2.远程查询购物车所有选中的购物项
            List<OrderItemVO> items = cartFeignService.getCurrentUserCartItems();
            orderConfirmVo.setItems(items);
        }, executor).thenRunAsync(() -> {
            List<OrderItemVO> items = orderConfirmVo.getItems();
            List<Long> collect = items.stream().map((item) -> item.getSkuId()).collect(Collectors.toList());
            R r = wmsFeignService.getSkusHasStock(collect);
            List<SkuHasStockVo> data = r.getData("data", new TypeReference<List<SkuHasStockVo>>() {
            });
            if (data != null) {
                Map<Long, Boolean> stocks = data.stream().collect(Collectors.toMap((item) -> item.getSkuId(), item -> item.getHasStock()));
                orderConfirmVo.setStocks(stocks);
            }
        }, executor);

        //feign在远程调用之前会构造请求，会调用很多的拦截器
        //3.查询用户积分
        Integer integration = memberRespVo.getIntegration();
        orderConfirmVo.setIntegration(integration);
        //4.其他数据自动计算
        CompletableFuture.allOf(getAddressFuture, getItemsFuture).get();
        //TODO 5.防重令牌
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        orderConfirmVo.setOrderToken(token);
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(), token, 30, TimeUnit.MINUTES);

        return orderConfirmVo;
    }

    public OrderConfirmVo myConfirmOrder() throws Exception{
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo=LoginUserInterceptor.loginUser.get();
        //获取之前的请求
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> getAddressFuture=CompletableFuture.runAsync(()->{
            //每一个线程都共享之前的请求
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //远程查询所有收货地址列表
            List<MemberAddressVo> addresses = memberFeignService.getAddress(memberRespVo.getId());
            orderConfirmVo.setAddresses(addresses);
        },executor);
        CompletableFuture<Void> getItemsFuture=CompletableFuture.runAsync(()->{
            //每一个线程都共享之前的请求
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //远程查询所有购物项信息
            List<OrderItemVO> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
            orderConfirmVo.setItems(currentUserCartItems);
        },executor).thenRunAsync(()->{
            List<OrderItemVO> items = orderConfirmVo.getItems();
            List<Long> skuIds = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            //查找每个商品是否有货
            R r = wmsFeignService.getSkusHasStock(skuIds);
            List<SkuHasStockVo> skuHasStockVoList = r.getData("data", new TypeReference<List<SkuHasStockVo>>() {
            });
            Map<Long, Boolean> collect = skuHasStockVoList.stream().collect(Collectors.toMap(k -> k.getSkuId(), v -> v.getHasStock()));
            orderConfirmVo.setStocks(collect);
        },executor);
        //查询用户积分
        Integer integration = memberRespVo.getIntegration();
        orderConfirmVo.setIntegration(integration);
        CompletableFuture.allOf(getAddressFuture,getItemsFuture).get();
        String token=UUID.randomUUID().toString().replace("-","");
        orderConfirmVo.setOrderToken(token);
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId(),token,30,TimeUnit.MINUTES);
        return orderConfirmVo;
    }
    //    @Transactional
//    public void a(){
//        OrderServiceImpl o = (OrderServiceImpl) AopContext.currentProxy();
//        o.b();
//        o.c();
//    }
    //本地事务，在分布式系统下，只能控制住自己的回滚，控制不了其他服务的回滚
    //产生分布式事务，最大原因：网络问题+分布式
//    @GlobalTransactional //2pc不适用于高并发
    @Transactional
    @Override
    public SubmitOrderRespVo submitOrder(OrderSubmitVo submitVo) {
        submitVoThreadLocal.set(submitVo);
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        SubmitOrderRespVo orderRespVo = new SubmitOrderRespVo();
        orderRespVo.setCode(0);
        //创建订单，验令牌，验价格，锁库存...
        //1.验证令牌[令牌的对比和删除必须保证原子性]
        //返回 删除失败0 令牌校验失败/删除成功1 令牌校验成功
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = submitVo.getOrderToken();
        //原子验证令牌和删除令牌
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);
        if (result == 0) {
            //不通过
            orderRespVo.setCode(1);
            return orderRespVo;
        } else {
            //令牌验证通过
            //创建订单，验令牌，验价格，锁库存...
            //1.创建订单,订单项等信息
            OrderCreateTo order = createOrder();
            //2.验价
            BigDecimal payAmount = order.getOrderEntity().getPayAmount();
            BigDecimal payPrice = submitVo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                //金额对比成功
                //TODO 3.保存订单
                saveOrder(order);
                //4.库存锁定，只要有异常，回滚订单数据。
                //订单号，所有订单项（skuId,skuName,num）
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(order.getOrderEntity().getOrderSn());
                List<OrderItemEntity> orderItems = order.getOrderItems();
                List<OrderItemVO> collect = orderItems.stream().map(item -> {
                    OrderItemVO orderItemVO = new OrderItemVO();
                    orderItemVO.setCount(item.getSkuQuantity());
                    orderItemVO.setSkuId(item.getSkuId());
                    orderItemVO.setTitle(item.getSkuName());
                    return orderItemVO;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(collect);
                //TODO 4.远程锁库存
                //为了保证高并发，库存服务自己回滚 做法：订单服务发消息给库存服务
                //库存服务本身也可以使用自动解锁模式 使用消息队列完成
                R r = wmsFeignService.orderLock(wareSkuLockVo);
                if (r.getCode() == 0) {
                    //锁库存成功
                    orderRespVo.setOrderEntity(order.getOrderEntity());
                    //TODO 5.远程扣减积分 出异常
//                    int i=10/0;
                    //TODO 订单创建成功，发送消息给mq
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrderEntity());
                    return orderRespVo;
                } else {
                    //锁库存失败
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
//                    orderRespVo.setCode(3);
//
//                    return orderRespVo;
                }
            } else {
                orderRespVo.setCode(2);
                return orderRespVo;
            }
        }
//        String redisToken = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId());
//        if(orderToken!=null&&orderToken.equals(redisToken)){
//            //令牌验证通过
//        } else {
//            //不通过
//
//        }
    }
    public SubmitOrderRespVo mySubmitOrder(OrderSubmitVo submitVo){
        submitVoThreadLocal.set(submitVo);
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        SubmitOrderRespVo orderRespVo = new SubmitOrderRespVo();
        orderRespVo.setCode(0);
        //创建订单，验令牌，验价格，锁库存...
        //1.验证令牌[令牌的对比和删除必须保证原子性]
        //返回 删除失败0 令牌校验失败/删除成功1 令牌校验成功
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = submitVo.getOrderToken();
        //原子验证令牌和删除令牌
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);
        if(result==0){
            //令牌验证不通过
            orderRespVo.setCode(1);
            return orderRespVo;
        }else{
            //令牌验证通过
            //1.创建订单，订单项等信息
            OrderCreateTo order = createOrder();
            //2.验价
            BigDecimal payAmount = order.getOrderEntity().getPayAmount();
            BigDecimal payPrice = submitVo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                //金额对比成功，保存订单
                saveOrder(order);
                //库存锁定
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(order.getOrderEntity().getOrderSn());
                List<OrderItemEntity> orderItems = order.getOrderItems();
                List<OrderItemVO> collect = orderItems.stream().map(item -> {
                    OrderItemVO orderItemVO = new OrderItemVO();
                    orderItemVO.setSkuId(item.getSkuId());
                    orderItemVO.setTitle(item.getSkuName());
                    orderItemVO.setCount(item.getSkuQuantity());
                    return orderItemVO;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(collect);
                //远程锁库存
                R r = wmsFeignService.orderLock(wareSkuLockVo);
                if(r.getCode()==0){
                    //锁库存成功
                    orderRespVo.setOrderEntity(order.getOrderEntity());
                    //TODO 订单创建成功，发送消息给mq
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrderEntity());
                    return orderRespVo;
                }else {
                    //锁库存失败
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }
            }else {
                orderRespVo.setCode(2);
                return orderRespVo;
            }
        }
    }
    private OrderCreateTo createOrder() {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        OrderEntity orderEntity = buildOrder();

        //2.获取所有的订单项信息
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderEntity.getOrderSn());

        //3.计算价格相关
        computePrice(orderEntity, orderItemEntities);

        orderCreateTo.setOrderEntity(orderEntity);
        orderCreateTo.setOrderItems(orderItemEntities);
        return orderCreateTo;
    }
    private OrderEntity buildOrder() {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        OrderEntity orderEntity = new OrderEntity();
        //创建订单号
        String orderSn = IdWorker.getTimeId();
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberId(memberRespVo.getId());
        //获取收获地址信息
        OrderSubmitVo orderSubmitVo = submitVoThreadLocal.get();
        R r = wmsFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo data = r.getData(new TypeReference<FareVo>() {
        });
        //设置运费信息
        BigDecimal fare = data.getFare();
        orderEntity.setFreightAmount(fare);
        //设置收货人信息
        MemberAddressVo memberAddressVo = data.getMemberAddressVo();
        orderEntity.setReceiverName(memberAddressVo.getName());
        orderEntity.setReceiverCity(memberAddressVo.getCity());
        orderEntity.setReceiverProvince(memberAddressVo.getProvince());
        orderEntity.setReceiverPhone(memberAddressVo.getPhone());
        orderEntity.setReceiverDetailAddress(memberAddressVo.getDetailAddress());
        orderEntity.setReceiverPostCode(memberAddressVo.getPostCode());
        orderEntity.setReceiverRegion(memberAddressVo.getRegion());
        //设置订单状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setConfirmStatus(7);
        return orderEntity;
    }
    @Override
    public OrderEntity getOrderStatusByOrderSn(String orderSn) {
        OrderEntity order = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order;
    }

    @Override
    public void closeOrder(OrderEntity order) {
        //查询这个订单的最新状态
        OrderEntity byId = this.getById(order.getId());
        if (byId.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()) {
            //关单
            OrderEntity orderEntity = new OrderEntity();
            orderEntity.setId(byId.getId());
            orderEntity.setStatus(OrderStatusEnum.CANCLED.getCode());
            order.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(orderEntity);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(order, orderTo);
            //发给mq订单关单成功信息
            try {
                //TODO 保证消息一定会发送出去，每一个消息都可以做好日志记录。（给数据库保存每一个消息的详细信息）
                //TODO 定期扫描数据库，将失败的消息再发送一遍
                rabbitTemplate.convertAndSend("order-event-exchange",
                        "order.release.other",
                        orderTo
                );
            } catch (Exception e) {
                //TODO 将没发送成功的消息 进行重试发送
            }

        }

    }

    /**
     * 获取当前订单的支付信息
     *
     * @param orderSn
     * @return
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        OrderEntity order = this.getOrderStatusByOrderSn(orderSn);
        PayVo payVo = new PayVo();

        payVo.setOut_trade_no(orderSn);//订单号
        OrderItemEntity one = orderItemService.getOne(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        payVo.setSubject(one.getSkuName());//订单的标题
        payVo.setBody(one.getSkuAttrsVals());//订单备注
        BigDecimal payAmount = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(payAmount.toString());//订单的金额
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberRespVo.getId()).orderByDesc("id")
        );
        List<OrderEntity> orderList = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemList = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(itemList);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(orderList);
        return new PageUtils(page);
    }


    /**
     * 处理支付宝的支付结果
     *
     * @param asyncVo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo asyncVo) {
        //1.保存交易流水
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setAlipayTradeNo(asyncVo.getTrade_no());
        paymentInfoEntity.setOrderSn(asyncVo.getOut_trade_no());
        paymentInfoEntity.setPaymentStatus(asyncVo.getTrade_status());
        paymentInfoEntity.setCallbackTime(asyncVo.getNotify_time());
        paymentInfoService.save(paymentInfoEntity);
        //2.修改订单状态
        if (asyncVo.getTrade_status().equals("TRADE_SUCCESS") || asyncVo.getTrade_status().equals("TRADE_FINISH")){
            String out_trade_no = asyncVo.getOut_trade_no();
            this.baseMapper.updateStatusByOrderSn(out_trade_no,OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    @Transactional
    @Override
    public void createSeckillOrder(SeckillOrderTo to) {
        //TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(to.getOrderSn());
        orderEntity.setMemberId(to.getMemberId());
        BigDecimal multiply = to.getSeckillPrice().multiply(new BigDecimal(to.getNum()));
        orderEntity.setPayAmount(multiply);
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        save(orderEntity);
        //TODO 保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setSkuId(to.getSkuId());
        orderItemEntity.setOrderSn(to.getOrderSn());
        orderItemEntity.setRealAmount(multiply);
        orderItemEntity.setSkuQuantity(to.getNum());
        //TODO 获取当前sku的详细信息进行设置
        orderItemService.save(orderItemEntity);
    }

    /**
     * 保存订单数据
     *
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrderEntity();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }



    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        BigDecimal totalPrice = new BigDecimal("0.0");
        BigDecimal integrationPrice = new BigDecimal("0.0");
        BigDecimal couponPrice = new BigDecimal("0.0");
        BigDecimal promotionPrice = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        //订单的总额，叠加每个订单项的总额
        for (OrderItemEntity orderItemEntity : orderItemEntities) {
            BigDecimal realAmount = orderItemEntity.getRealAmount();
            BigDecimal integrationAmount = orderItemEntity.getIntegrationAmount();
            BigDecimal couponAmount = orderItemEntity.getCouponAmount();
            BigDecimal promotionAmount = orderItemEntity.getPromotionAmount();
            Integer giftIntegration = orderItemEntity.getGiftIntegration();
            Integer giftGrowth = orderItemEntity.getGiftGrowth();


            totalPrice = totalPrice.add(realAmount);
            integrationPrice = integrationPrice.add(integrationAmount);
            couponPrice = couponPrice.add(couponAmount);
            promotionPrice = promotionPrice.add(promotionAmount);
            integration = integrationAmount.add(new BigDecimal(giftIntegration.toString()));
            growth = integration.add(new BigDecimal(growth.toString()));
        }
        //1.订单价格相关
        orderEntity.setTotalAmount(totalPrice);
        //应付总额
        orderEntity.setPayAmount(totalPrice.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotionPrice);
        orderEntity.setIntegrationAmount(integrationPrice);
        orderEntity.setCouponAmount(couponPrice);
        //设置积分 成长值
        orderEntity.setIntegration(integration.intValue());
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setDeleteStatus(0);
    }



    /**
     * 构建所有订单项
     *
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //2.获取所有的订单项信息
        //最后确定每个购物项的价格
        List<OrderItemVO> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if (currentUserCartItems != null && currentUserCartItems.size() > 0) {
            List<OrderItemEntity> items = currentUserCartItems.stream().map((item) -> {
                OrderItemEntity orderItemEntity = buildOrderItem(item);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
            return items;
        }
        return null;
    }

    /**
     * 构建某个订单项
     */
    private OrderItemEntity buildOrderItem(OrderItemVO cartItem) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();

        //1.订单信息 订单号

        //2.Spu信息
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuId(data.getId());
        orderItemEntity.setSpuBrand(data.getBrandId() + "");
        orderItemEntity.setSpuName(data.getSpuName());
        orderItemEntity.setCategoryId(data.getCatalogId());
        //3.sku信息
        orderItemEntity.setSkuId(cartItem.getSkuId());
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPic(cartItem.getImage());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        String string = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(string);
        orderItemEntity.setSkuQuantity(cartItem.getCount());
        //4.优惠信息【忽略】

        //5.赠送积分信息
        orderItemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        orderItemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        //6.订单项价格信息
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
        BigDecimal originPrice = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        //当前订单实际金额 总额减各种优惠
        BigDecimal realPrice = originPrice.subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(realPrice);
        return orderItemEntity;
    }
}